<template>
    <div class="user-center-container">
        <el-card class="user-info-card">
            <el-avatar :src="userInfo.avatar" size="large" />
            <div class="user-info">
                <div>昵称：{{ userInfo.nickname }}</div>
                <div>手机号：{{ userInfo.mobile }}</div>
                <div>角色：{{ userInfo.role }}</div>
                <div>注册时间：{{ userInfo.gmtCreate }}</div>
                <el-button type="primary" @click="openEditDialog" size="small">编辑资料</el-button>
                <el-button type="default" @click="pwdDialogVisible = true" size="small" style="margin-left: 12px;">修改密碼</el-button>
            </div>
        </el-card>
        <el-tabs v-model="activeTab" class="user-tabs">
            <el-tab-pane label="我的发帖" name="posts">
                <!-- 帖子列表 -->
                <el-table :data="myPosts">
                    <el-table-column prop="content" label="内容" />
                    <el-table-column prop="gmtCreate" label="时间" />
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="我的回复" name="replies">
                <!-- 回复列表 -->
                <el-table :data="myReplies">
                    <el-table-column prop="content" label="内容" />
                    <el-table-column prop="gmtCreate" label="时间" />
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <!-- 编辑资料弹窗 -->
        <el-dialog v-model="editDialogVisible" title="编辑资料">
            <div style="margin-bottom: 16px; text-align:center;">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:10010/edu_oss/fileoss/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="uploadHeaders"
                >
                    <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" style="width:60px;height:60px;border-radius:50%" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>
            <el-form :model="editForm">
                <el-form-item label="昵称">
                    <el-input v-model="editForm.nickname" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveProfile">保存</el-button>
            </template>
        </el-dialog>

        <!-- 修改密碼彈窗 -->
        <el-dialog v-model="pwdDialogVisible" title="修改密碼">
            <el-form :model="pwdForm">
                <el-form-item label="舊密碼">
                    <el-input v-model="pwdForm.oldPassword" type="password" />
                </el-form-item>
                <el-form-item label="新密碼">
                    <el-input v-model="pwdForm.newPassword" type="password" />
                </el-form-item>
                <el-form-item label="確認新密碼">
                    <el-input v-model="pwdForm.confirmPassword" type="password" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="pwdDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="changePassword">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const userInfo = ref({})
const myPosts = ref([])
const myReplies = ref([])
const activeTab = ref('posts')
const editDialogVisible = ref(false)
const editForm = ref({ nickname: '', avatar: '' })
const pwdDialogVisible = ref(false)
const pwdForm = ref({ oldPassword: '', newPassword: '', confirmPassword: '' })
// 修正：在 setup 裡定義 uploadHeaders
const uploadHeaders = ref({
  Authorization: 'Bearer ' + (localStorage.getItem('token') || '')
})

const fetchUserInfo = async () => {
    const token = localStorage.getItem('token')
    if (token) {
        const res = await axios.get('http://localhost:10010/serviceUcenter/ucenter/getUserInfoForJwt', {
            headers: { Authorization: `Bearer ${token}` }
        })
        if (res.data && res.data.success) {
            userInfo.value = res.data.data.userInfo
            editForm.value.nickname = userInfo.value.nickname
            editForm.value.avatar = userInfo.value.avatar
        }
    }
}
const fetchMyPosts = async () => {
    const res = await axios.get('http://localhost:10010/eduservice/edu-comment/myPosts', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    if (res.data && res.data.success) {
        myPosts.value = res.data.data.list || []
    }
}
const fetchMyReplies = async () => {
    const res = await axios.get('http://localhost:10010/eduservice/edu-comment/myReplies', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    if (res.data && res.data.success) {
        myReplies.value = res.data.data.list || []
    }
}
const openEditDialog = () => {
    editForm.value.nickname = userInfo.value.nickname || ''
    editForm.value.avatar = userInfo.value.avatar || ''
    editDialogVisible.value = true
}
const saveProfile = async () => {
    const res = await axios.post('http://localhost:10010/serviceUcenter/ucenter/updateProfile', editForm.value, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    if (res.data && res.data.success) {
        userInfo.value.nickname = editForm.value.nickname
        userInfo.value.avatar = editForm.value.avatar
        editDialogVisible.value = false
        ElMessage.success('保存成功')
    } else {
        ElMessage.error(res.data.message || '保存失敗')
    }
}
const handleAvatarSuccess = (response) => {
    if (response.data && response.data.url) {
        editForm.value.avatar = response.data.url
        ElMessage.success('頭像上傳成功')
    }
}
const changePassword = async () => {
    if (pwdForm.value.newPassword !== pwdForm.value.confirmPassword) {
        ElMessage.error('兩次新密碼不一致')
        return
    }
    const token = localStorage.getItem('token')
    try {
        const res = await axios.post('http://localhost:10010/serviceUcenter/ucenter/changePassword', {
            oldPassword: pwdForm.value.oldPassword,
            newPassword: pwdForm.value.newPassword
        }, {
            headers: { Authorization: `Bearer ${token}` }
        })
        if (res.data && res.data.success) {
            ElMessage.success('密碼修改成功，請重新登錄')
            pwdDialogVisible.value = false
            // 可選：自動退出登錄
            // localStorage.removeItem('token')
            // location.reload()
        } else {
            ElMessage.error(res.data.message || '密碼修改失敗')
        }
    } catch (e) {
        ElMessage.error(e.response?.data?.message || '密碼修改失敗')
    }
}

onMounted(() => {
    fetchUserInfo()
    fetchMyPosts()
    fetchMyReplies()
})
</script>

<style scoped>
.user-center-container {
    max-width: 900px;
    margin: 40px auto;
    padding: 24px;
}
.user-info-card {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
}
.user-info {
    margin-left: 24px;
}
.user-tabs {
    background: #fff;
    border-radius: 12px;
    padding: 24px;
}
</style>